package com.cloud.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 2020/3/18
 * Zuul过滤器
 *
 * @author machuanpeng
 */
@Component
public class MyZuulFilter extends ZuulFilter {
    /**
     * pre:路由前过滤，route:路由时过滤，post:路由后过滤，error:用于错误处理.
     * 2020/3/18
     *
     * @param
     * @return java.lang.String
     * @author machuanpeng
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 过滤的顺序.
     * 2020/3/18
     *
     * @param
     * @return int
     * @author machuanpeng
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否要过滤.
     * 2020/3/18
     *
     * @param
     * @return boolean
     * @author machuanpeng
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器的具体逻辑.
     * 2020/3/18
     *
     * @param
     * @return java.lang.Object
     * @author machuanpeng
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        System.out.println(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        Object accessToken = request.getParameter("token");
        if (accessToken == null) {
            System.out.println("token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("token is empty");
            } catch (Exception e) {
                System.out.println("异常处理");
            }
            return null;
        }
        System.out.println("ok");
        return null;
    }
}
